package com.tebiecloud.goods.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tebiecloud.act.client.model.entity.Act;
import com.tebiecloud.act.client.model.entity.ActGiftPack;
import com.tebiecloud.act.client.model.entity.ActGoodsRef;
import com.tebiecloud.act.client.model.vo.ActListVO;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.BeanConvertUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.goods.client.model.entity.*;
import com.tebiecloud.goods.client.model.vo.*;
import com.tebiecloud.goods.server.mapper.*;
import com.tebiecloud.goods.server.service.GoodsProcessService;
import com.tebiecloud.goods.server.service.GoodsService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.goods.server.service.feign.ActGoodsRefServiceClient;
import com.tebiecloud.goods.server.service.feign.ActServiceClient;
import com.tebiecloud.goods.server.service.feign.StoreServiceClient;
import com.tebiecloud.store.client.model.entity.Store;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 商品表 服务实现类
 * @author tebie
 * @date 2019-09-12
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class GoodsServiceImpl extends BaseServiceImpl<GoodsMapper, Goods> implements GoodsService {

    @Autowired
    GoodsMapper goodsMapper;

    @Autowired
    GoodsCollectMapper goodsCollectMapper;

    @Autowired
    GoodsSpecificationMapper goodsSpecificationMapper;

    @Autowired
    ActGoodsRefServiceClient actGoodsRefServiceClient;

    @Autowired
    ActServiceClient actServiceClient;

    @Autowired
    private StoreServiceClient storeServiceClient;

    @Autowired
    private GoodsProcessMapper goodsProcessMapper;

    @Autowired
    private GoodsNoticeMapper goodsNoticeMapper;

    @Override
    public IPage<GoodsListVO> listGoods(Integer page, Integer limit, long storeId) {
        IPage<GoodsListVO> goodsListVOIPage = new Page<>();
        List<GoodsListVO> goodsListVOS = new ArrayList<>();
        //查询该门店所有商品
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("store_id",storeId);
        goodsQueryWrapper.eq("down",0);
        goodsQueryWrapper.eq("deleted",0);
        goodsQueryWrapper.orderByDesc("sort");
        IPage<Goods> goodsIPage = goodsMapper.selectPage(new PageParams(page,limit),goodsQueryWrapper);
        for(Goods goods:goodsIPage.getRecords()){
            //赋值新的的返回对象
            GoodsListVO goodsListVO = new GoodsListVO();
            //循环查询是否参与限时活动
            ResultBody<List<ActGoodsRef>> actGoodsResultBody = actGoodsRefServiceClient.listActGoodsRefByGoodsId(goods.getGoodsId(),1);
            if(actGoodsResultBody!=null && actGoodsResultBody.getCode() == ResultEnum.OK.getCode()){
                List<ActGoodsRef> actGoodsRefList = actGoodsResultBody.getData();
                if(actGoodsRefList.size()>0){
                    //查询活动信息
                    ResultBody<ActListVO> actInfoVOResultBody = actServiceClient.selectActByActIdAndGoodsId(actGoodsRefList.get(0).getActId(),goods.getGoodsId());
                    if(actInfoVOResultBody!=null && actInfoVOResultBody.getCode() == ResultEnum.OK.getCode()){
                        ActListVO actListVO = actInfoVOResultBody.getData();
                        goodsListVO.setActId(actListVO.getActId());
                        goodsListVO.setGoodsId(goods.getGoodsId());
                        goodsListVO.setGoodsName(actListVO.getActName());
                        goodsListVO.setSpecName(actListVO.getSpecName());
                        goodsListVO.setGoodsType(2);
                        goodsListVO.setMainPic(actListVO.getMainPic());
                        goodsListVO.setPrice(actListVO.getPrice());
                        goodsListVO.setRetailPrice(actListVO.getRetailPrice());
                        goodsListVO.setShelfTime(actListVO.getShelfTime());
                        goodsListVO.setStartTime(actListVO.getStartTime());
                        goodsListVO.setEndTime(actListVO.getEndTime());
                        goodsListVO.setPurchaseStatus(actListVO.getPurchaseStatus());
                    }else {
                        log.info(">>minjie 查询没有活动");
                    }
                }else{
                    //如果不是活动商品
                    goodsListVO.setGoodsId(goods.getGoodsId());
                    goodsListVO.setGoodsName(goods.getName());
                    goodsListVO.setMainPic(goods.getMainPic());
                    //查询规格列表
                    QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
                    goodsSpecificationQueryWrapper.eq("goods_id",goods.getGoodsId());
                    goodsSpecificationQueryWrapper.eq("down",0);
                    goodsSpecificationQueryWrapper.eq("deleted",0);
                    List<GoodsSpecification> goodsSpecificationList = goodsSpecificationMapper.selectList(goodsSpecificationQueryWrapper);
                    if(goodsSpecificationList.size()>0){
                        int j = 0;//获取价格最小的规格
                        int stockQty = 0; //计算库存
                        for(int i=0;i<goodsSpecificationList.size();i++){
                            if(stockQty!=-99)stockQty = stockQty + goodsSpecificationList.get(i).getStockQty();
                            if(i==0)j=0;
                            if(goodsSpecificationList.get(i).getPrice()<goodsSpecificationList.get(j).getPrice()){
                                j = i;
                            }
                        }
                        goodsListVO.setSpecName(goodsSpecificationList.get(j).getName());
                        goodsListVO.setGoodsType(1);
                        goodsListVO.setPrice(goodsSpecificationList.get(j).getPrice());
                        goodsListVO.setRetailPrice(goodsSpecificationList.get(j).getRetailPrice());
                        if(stockQty==0){
                            goodsListVO.setPurchaseStatus(3);
                        }else{
                            goodsListVO.setPurchaseStatus(2);
                        }
                    }else{
                        log.info(">>minjie 查询没有规格");
                    }

                }
            }else {
                log.info(">>minjie 查询限时活动出错");
            }
            //赋值给对象数组
            goodsListVOS.add(goodsListVO);
        }
        //最后赋值给分页对象
        goodsListVOIPage.setTotal(goodsIPage.getTotal());
        goodsListVOIPage.setSize(goodsIPage.getSize());
        goodsListVOIPage.setPages(goodsIPage.getPages());
        goodsListVOIPage.setCurrent(goodsIPage.getCurrent());
        goodsListVOIPage.setRecords(goodsListVOS);
        return goodsListVOIPage;
    }

    @Override
    public GoodsVO info(long goodsId,Long actId) {
        GoodsVO goodsVO = new GoodsVO();
        //获取商品信息
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        goodsQueryWrapper.eq("goods_id", goodsId);
        Goods goods = goodsMapper.selectOne(goodsQueryWrapper);
        goodsVO.setIsAnyRefund(goods.getIsAnyRefund());
        goodsVO.setIsStoreService(goods.getIsStoreService());
        goodsVO.setIsReserve(goods.getIsReserve());
        //查询是否收藏
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if (securityUserDetails != null) {
            QueryWrapper<GoodsCollect> actCollectQueryWrapper = new QueryWrapper<>();
            actCollectQueryWrapper.eq("user_id", securityUserDetails.getUserId());
            actCollectQueryWrapper.eq("goods_id", goodsId);
            List<GoodsCollect> goodsCollectList = goodsCollectMapper.selectList(actCollectQueryWrapper);
            if (goodsCollectList != null && goodsCollectList.size() > 0) {
                goodsVO.setIsCollect(1); //已收藏
            } else {
                goodsVO.setIsCollect(0); //未收藏
            }
        }
        //首先校验该活动是否存在
        if (actId != null){
            long currentTime = System.currentTimeMillis();
            ResultBody<Act> actResultBody = actServiceClient.selectActByActId(actId);
            if(actResultBody!=null && actResultBody.getCode() == ResultEnum.OK.getCode()){
                Act act = actResultBody.getData();
                if(act!=null && act.getStatus().equals(1)
                        && currentTime>=act.getShelfTime().getTime() && currentTime<=act.getEndTime().getTime()){
                    actId = act.getActId();
                }else{
                    actId = null;
                }
            }
        }
        if(actId == null){
            //先查询是否有关联活动
            ResultBody<List<ActGoodsRef>> actGoodsResultBody = actGoodsRefServiceClient.listActGoodsRefByGoodsId(goods.getGoodsId(),1);
            if(actGoodsResultBody!=null && actGoodsResultBody.getCode() == ResultEnum.OK.getCode()){
                List<ActGoodsRef> actGoodsRefList = actGoodsResultBody.getData();
                if(actGoodsRefList!=null && actGoodsRefList.size()>0){
                    actId = actGoodsRefList.get(0).getActId();
                }
            }
        }
        if (actId != null) {
            //查询活动信息
            ResultBody<ActListVO> actInfoVOResultBody = actServiceClient.selectActByActIdAndGoodsId(actId, goods.getGoodsId());
            if (actInfoVOResultBody != null && actInfoVOResultBody.getCode() == ResultEnum.OK.getCode()) {
                ActListVO actListVO = actInfoVOResultBody.getData();
                goodsVO.setActId(actListVO.getActId());
                goodsVO.setGoodsId(goods.getGoodsId());
                goodsVO.setGoodsName(actListVO.getActName());
                goodsVO.setIsAnyRefund(actListVO.getIsRefundable());
                goodsVO.setGoodsType(2);
                goodsVO.setCarouselPics(actListVO.getCarouselPics());
                goodsVO.setDetailPics(actListVO.getDetailPics());
                goodsVO.setSharePic(actListVO.getSharePic());
                goodsVO.setShareTitle(actListVO.getShareTitle());
                goodsVO.setShareRemark(actListVO.getShareRemark());
                goodsVO.setRemainTime(actListVO.getRemainTime());
                goodsVO.setShelfTime(actListVO.getShelfTime());
                goodsVO.setStartTime(actListVO.getStartTime());
                goodsVO.setEndTime(actListVO.getEndTime());
                goodsVO.setPurchaseStatus(actListVO.getPurchaseStatus());
                int actPrice = 0;//活动价格
                int actRetailPrice = 0;//活动门市价
                if(actListVO.getActType() == 2){
                    //获取体验商品的价格
                    ResultBody<ActGiftPack> actGiftPackResultBody = actServiceClient.selectActGift(actId);
                    if(actGiftPackResultBody!=null && actGiftPackResultBody.getCode() == ResultEnum.OK.getCode()){
                        ActGiftPack actGiftPack = actGiftPackResultBody.getData();
                        if(actGiftPack!=null){
                            actPrice = actGiftPack.getPrice();
                            actRetailPrice = actGiftPack.getRetailPrice();
                        }
                    }
                }
                List<ProcessVO> processVOList = Lists.newArrayList();
                //查询活动的规格
                ResultBody<List<ActGoodsRef>> resultBody = actGoodsRefServiceClient.listActGoodsRefByActIdAndGoodsId(actId, goods.getGoodsId());
                if (resultBody != null && resultBody.getCode() == ResultEnum.OK.getCode()) {
                    List<ActGoodsRef> actGoodsRefList1 = resultBody.getData();
                    List<GoodsSpecListVO> goodsSpecListVOList = new ArrayList<>();
                    for (ActGoodsRef actGoodsRef : actGoodsRefList1) {
                        GoodsSpecListVO goodsSpecListVO = new GoodsSpecListVO();
                        goodsSpecListVO.setPrice(actPrice==0?actGoodsRef.getPrice():actPrice);
                        goodsSpecListVO.setRetailPrice(actRetailPrice==0?actGoodsRef.getRetailPrice():actRetailPrice);
                        goodsSpecListVO.setSpecId(actGoodsRef.getSpecId());
                        if(actGoodsRef.getStockQty()>0 || actGoodsRef.getStockQty().equals(-99)){
                            goodsSpecListVO.setIsOptional(1);
                        }else{
                            goodsSpecListVO.setIsOptional(0);
                        }
                        //获取规格名称
                        QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
                        goodsSpecificationQueryWrapper.eq("goods_id", goods.getGoodsId());
                        goodsSpecificationQueryWrapper.eq("spec_id", actGoodsRef.getSpecId());
                        goodsSpecificationQueryWrapper.eq("deleted", 0);
                        GoodsSpecification goodsSpecification = goodsSpecificationMapper.selectOne(goodsSpecificationQueryWrapper);
                        goodsSpecListVO.setSpenName(goodsSpecification.getName());
                        goodsSpecListVOList.add(goodsSpecListVO);
                        //查询规格流程
                        if(goodsSpecification.getGoodsProcessId()!=null){
                            GoodsProcess goodsProcess = selectGoodsProcess(goodsSpecification.getGoodsProcessId());
                            ProcessVO processVO = BeanConvertUtils.convertBean(goodsProcess,ProcessVO.class);
                            processVO.setSpenName(goodsSpecification.getName());
                            processVOList.add(processVO);
                        }
                    }
                    goodsVO.setGoodsSpecList(goodsSpecListVOList);
                    goodsVO.setProcessList(processVOList);
                }
            }
        } else {
            //如果不是活动商品
            goodsVO.setGoodsType(1);
            goodsVO.setGoodsId(goods.getGoodsId());
            goodsVO.setGoodsName(goods.getName());
            String[] carouselPics = goods.getCarouselPics().split(",");
            String[] detailPics = goods.getDetailPics().split(",");
            goodsVO.setCarouselPics(Arrays.asList(carouselPics));
            goodsVO.setDetailPics(Arrays.asList(detailPics));
            goodsVO.setSharePic(goods.getSharePic());
            goodsVO.setShareTitle(goods.getShareTitle());
            goodsVO.setShareRemark(goods.getShareRemark());
            //查询规格列表
            QueryWrapper<GoodsSpecification> goodsSpecificationQueryWrapper = new QueryWrapper<>();
            goodsSpecificationQueryWrapper.eq("goods_id", goods.getGoodsId());
            goodsSpecificationQueryWrapper.eq("down", 0);
            goodsSpecificationQueryWrapper.eq("deleted", 0);
            List<GoodsSpecification> goodsSpecificationList = goodsSpecificationMapper.selectList(goodsSpecificationQueryWrapper);
            List<GoodsSpecListVO> goodsSpecListVOList = new ArrayList<>();
            int stockQty = 0;
            List<ProcessVO> processVOList = Lists.newArrayList();
            for (GoodsSpecification goodsSpecification : goodsSpecificationList) {
                GoodsSpecListVO goodsSpecListVO = new GoodsSpecListVO();
                goodsSpecListVO.setPrice(goodsSpecification.getPrice());
                goodsSpecListVO.setRetailPrice(goodsSpecification.getRetailPrice());
                goodsSpecListVO.setSpecId(goodsSpecification.getSpecId());
                goodsSpecListVO.setSpenName(goodsSpecification.getName());
                if(goodsSpecification.getStockQty()>0){
                    goodsSpecListVO.setIsOptional(1);
                }else{
                    goodsSpecListVO.setIsOptional(0);
                }
                goodsSpecListVOList.add(goodsSpecListVO);
                if (stockQty != -99) stockQty = goodsSpecification.getStockQty() + stockQty;
                //查询规格流程
                if(goodsSpecification.getGoodsProcessId()!=null){
                   GoodsProcess goodsProcess = selectGoodsProcess(goodsSpecification.getGoodsProcessId());
                    ProcessVO processVO = BeanConvertUtils.convertBean(goodsProcess,ProcessVO.class);
                    processVO.setSpenName(goodsSpecification.getName());
                    processVOList.add(processVO);
                }
            }
            goodsVO.setProcessList(processVOList);
            goodsVO.setGoodsSpecList(goodsSpecListVOList);
            if (stockQty != 0) {
                goodsVO.setPurchaseStatus(2);
            } else {
                goodsVO.setPurchaseStatus(3);
            }

        }

        //获取门店信息
        ResultBody<List<Store>> storeResultBody = storeServiceClient.selectStoreList(goods.getStoreId().toString());
        if (storeResultBody != null && storeResultBody.getCode() == ResultEnum.OK.getCode()) {
            List<Store> storeList = storeResultBody.getData();
            StoreVO storeVO = new StoreVO();
            //计算距离
            if (storeList != null && storeList.size() > 0) {
                storeVO.setStoreName(storeList.get(0).getName());
                storeVO.setStorePhone(storeList.get(0).getStorePhone());
                storeVO.setAddress(storeList.get(0).getAddress());
                storeVO.setLng(storeList.get(0).getLng());
                storeVO.setLat(storeList.get(0).getLat());
                goodsVO.setStore(storeVO);
            }
        }
        //获取购买须知
        GoodsNotice goodsNotice = selectGoodsNotice(goodsId);
        goodsVO.setGoodsNotice(goodsNotice);
        return goodsVO;
    }

    /**
     * 获取规格流程
     * @param goodsProcessId
     * @return
     */
    private GoodsProcess selectGoodsProcess(long goodsProcessId){
        QueryWrapper<GoodsProcess> goodsProcessQueryWrapper = new QueryWrapper<>();
        goodsProcessQueryWrapper.eq("goods_process_id",goodsProcessId);
        goodsProcessQueryWrapper.eq("deleted",0);
        GoodsProcess goodsProcess = goodsProcessMapper.selectOne(goodsProcessQueryWrapper);
        return goodsProcess;
    }

    /**
     * 获取购买须知
     * @param goodsId
     * @return
     */
    private GoodsNotice selectGoodsNotice(long goodsId){
        QueryWrapper<GoodsNotice> goodsNoticeQueryWrapper = new QueryWrapper<>();
        goodsNoticeQueryWrapper.eq("goods_id",goodsId);
        goodsNoticeQueryWrapper.eq("deleted",0);
        GoodsNotice goodsNotice = goodsNoticeMapper.selectOne(goodsNoticeQueryWrapper);
        return goodsNotice;
    }
}
